<template>
  <!--搜索-->
  <a-form
      ref="searchForm"
      layout="inline"
      :model="form.defSearch"
      :rules="form.defSearchRules"
      style="display: flex;flex-wrap:wrap;"
      class="_magt20 go_shadow go_radius ">

    <a-form-item label="API名称" name="name" class="_230w ">
      <a-auto-complete
          v-model:value="form.defSearch.name"
          placeholder="请输入API名称"
          :allowClear="true"
          :options="auto.name"
          @keyup.enter.prevent="queryPage_"
          @search="(value) => { searchAsync_( value, 'name' )}"
      >
        <template #option="item">
          <div @click="searchSelect_(item.name,'name',item)"> {{ item.name }}</div>
        </template>
      </a-auto-complete>
    </a-form-item>

    <a-form-item label="访问地址" name="path" class="_270w ">
      <a-auto-complete
          v-model:value="form.defSearch.path"
          placeholder="请输入API访问地址"
          :allowClear="true"
          :options="auto.path"
          @keyup.enter.prevent="queryPage_"
          @search="(value) => { searchAsync_( value, 'path' )}"
      >
        <template #option="item">
          <div @click="searchSelect_(item.path,'path',item)"> {{ item.path }}</div>
        </template>
      </a-auto-complete>
    </a-form-item>

    <div style="flex: 1 1 0;"/>

    <a-form-item style="margin-right: 0">
      <a-button type="primary" @click="queryPage_">查询</a-button>
      <a-button style="margin-left: 10px" @click="()=>{ resetForm_('searchForm');  }">重置</a-button>
    </a-form-item>
    <!--      <el-form-item>-->
    <!--        <el-button type="primary" @click="queryPage_">查询</el-button>-->
    <!--        <el-button @click="()=>{ resetForm_('searchForm'); queryPage_() }">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

  </a-form>

  <!--表格-->
  <a-table rowKey="id"
           :pagination="false"
           :size="table.defSize"
           :style="{height:tableHeight+'px',marginTop:20+'px'}"
           :scroll="{ y: tableHeight }"
           :columns="table.defColumn"
           :data-source="table.defData"
           :defClickRow="defClickRow"
           :customRow="defCustomRow "
           :rowSelection="defRowSelection_()">

    <template #bodyCell="{ text, record, index, column  }">

      <template v-if="column.dataIndex === 'name'">
        <component :is="$icons[record.icon]"
                   style="border: 1px solid #EEEEEE; border-radius: 999px;padding: 5px;font-size: 20px;margin-right: 5px"/>
        <span>{{ text }}</span>
      </template>

      <template v-if="column.dataIndex === 'path'">
        <span v-if="text">{{ text }}</span>
        <span v-else>#</span>
      </template>

      <template v-if="column.dataIndex === 'action'">
        <a @click="openInfo_(record)">详情</a>
      </template>

    </template>
  </a-table>

  <!--编辑Dialog-->
  <a-modal
      v-model:visible="show.openInfo"
      title="API详情"
      width="1000px"
      :zIndex="1001"
      :footer="null"
      :destroyOnClose="true"
      :maskClosable="false">

    <!--编辑表单-->
    <a-form
        ref="defForm"
        :model="form.defData"
        :rules="form.defRules"
        :label-col="form.defLC"
        :wrapper-col="form.defWC"
        class="go_shadow go_radius">

      <a-form-item label="当前层级" name="level">
        <a-input v-model:value="form.defData.level" disabled/>
      </a-form-item>

      <a-form-item label="API名称" name="name">
        <a-input v-model:value="form.defData.name" placeholder="请输入API名称" :allowClear="true" readonly/>
      </a-form-item>

      <a-form-item label="请求地址" name="path">
        <a-input v-model:value="form.defData.path" placeholder="请输入请求地址" :allowClear="true" readonly/>
      </a-form-item>

      <a-form-item label="当前状态" name="is_use">
        <a-radio-group v-model:value="form.defData.is_use" disabled>
          <a-radio value="0">已启用</a-radio>
          <a-radio value="1">已禁用</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="权限校验" name="is_verify">
        <a-radio-group v-model:value="form.defData.is_verify" disabled>
          <a-radio value="0">开启</a-radio>
          <a-radio value="1">关闭</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="重复提交校验" name="is_re_submit">
        <a-radio-group v-model:value="form.defData.is_re_submit" disabled>
          <a-radio value="0">开启</a-radio>
          <a-radio value="1">关闭</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="访问间隔(秒)" name="access_time">
        <a-input-number v-model:value="form.defData.access_time" :min="0" :max="999999" readonly/>
        <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔（0代表无限制）</span>
      </a-form-item>

      <a-form-item label="间隔内访问次数" name="access_max_count">
        <a-input-number v-model:value="form.defData.access_max_count" :min="1" :max="999999" readonly/>
        <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔时间内的访问次数（默认为1）</span>
      </a-form-item>

      <a-form-item label="访问总次数" name="max_count">
        <a-input-number v-model:value="form.defData.max_count" :min="0" :max="999999" readonly/>
        <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问总次数（0代表无限制）</span>
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-input-number v-model:value="form.defData.sort" :min="1" :max="99999" readonly/>
      </a-form-item>

      <a-form-item label="描述信息" name="des">
        <a-textarea show-count :maxlength="200" v-model:value="form.defData.des" placeholder="请输入描述信息" :rows="3"
                    readonly/>
      </a-form-item>
    </a-form>

  </a-modal>

</template>

<script>

import {createVNode, defineComponent} from 'vue';
import screenfull from "screenfull";
import {Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import Icon from "@/common/component/Icon.vue";

export default defineComponent({
  name: 'SelectAPI',
  props: {
    //是否多选
    type: {
      type: Object,
      default: 'checkbox',//多选/单选，checkbox or radio
      required: false,
    },
    //默认选中
    defaultSelectKey: {
      type: Object,
      default: [],
      required: false,
    },
    //表格高度
    tableHeight: {
      type: Object,
      default: 400,
      required: false,
    },
  },
  components: {Icon},
  mounted() {
    ////////console.log(this.$route.path, ">>>>>>mounted")

    this.queryPage_()
    //全局监听-刷新
    this.$event.$on('refresh', (data) => {
      if ('/system/menu' == data['path']) {
        ////////console.log(this.$route.path, ">>>执行刷新界面>>>", data)
      }
    })
  },
  data() {
    return {

      //开关
      show: {
        openInfo: false,
      },

      //表格
      table: {
        defData: [],
        defColumn: [
          {title: 'API(ID)', dataIndex: 'id', width: 220},
          {title: 'API名称', dataIndex: 'name', width: 220},
          {title: '请求地址', dataIndex: 'path', width: 320},
          {title: '状态', dataIndex: 'is_use', align: 'center', width: 100},
          {title: '排序', dataIndex: 'sort', align: 'center', width: 100},
          {title: '操作', dataIndex: 'action', align: 'center', width: 200},
        ],
        defSelectKey: [],
        defSelectRow: [],
        defSize: 'small',
      },

      //表单
      form: {
        defData: {},
        defRules: {
          link_type: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          pname: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          level: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          menu_is_show: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          link_url: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          sort: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          name: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          path: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
        },
        defLC: {span: 4},
        defWC: {span: 16},
        defSearch: {
          name: "",
          path: "",
          link_type: undefined,
          menu_is_show: undefined,
        },
        defSearchRules: {},
        //(初始化/重置)Data
        defResetData: {
          pname: '#',
          level: '1',
          des: '',
          link_url: '',
          link_type: "0",
          pid: '0',
          sort: 100,
          menu_is_show: "0",
          tab_is_show: "0",
          tab_is_close: "0",
          tab_is_refresh: "0",
          tab_title_is_show: "0",
          tab_icon_is_show: "1",
          bre_is_show: "0",
          bre_title_is_show: "0",
          bre_icon_is_show: "1",
        },
      },

      //自动完成
      auto: {
        name: [],
      },

      //option选项
      option: {
        tableSize: [
          {key: 'default', text: '大号'},
          {key: 'middle', text: '中号'},
          {key: 'small', text: '小号'},
        ],
        menuIsSHow: [
          {label: '展示', value: '0'},
          {label: '隐藏', value: '1'},
        ],
        menuLinkType: [
          {label: '非链接', value: '0'},
          {label: '外部链接', value: '1'},
          {label: '内部链接', value: '2'},
        ]
      }
    };
  },
  methods: {
    openInfo_(recode) {
      this.show.openInfo = true
      this.form.defData = recode
    },
    queryPage_() {
      let param = {
        ...this.form.defSearch
      }
      this.$http.post('/system/api/page', param).then(res => {
        if (res.status) {
          this.table.defData = this.$kit.getTree(res.data)
        } else {
          this.$message.warning(res.message)
        }
      })
    }
    ,
//自动完成查询
    searchAsync_(str, type) {
      this.$http.post('/system/menu/searchInput', {[type]: str}).then(res => {
        this.auto[type] = res.data
      })
    }
    ,
//input异步查询-点击事件
    searchSelect_(value, type, item) {
      this.form.defSearch[type] = value
    }
    ,
//执行新增
    addDat() {
      this.$refs.defForm
          .validate()
          .then(() => {
            this.$http.post("/system/menu/add", this.form.defData).then(res => {
              if (res.status) {
                this.$message.success(res.message)
                this.queryPage_()
                this.show.insertDialog = false
              } else {
                this.$message.warning(res.message)
              }
            })
          })
          .catch(error => {
            ////////////console.log('error', error);
          });
    }
    ,
//执行编辑
    editDat() {
      this.$refs.defForm
          .validate()
          .then(() => {
            delete this.form.defData['children']
            this.$http.post("/system/menu/edit", this.form.defData).then(res => {
              if (res.status) {
                this.$message.success(res.message)
                this.queryPage_()
                this.show.editDialog = false
              } else {
                this.$message.warning(res.message)
              }
            })
          }).catch(error => {
        ////////////console.log('error', error);
      });
    }
    ,
//执行删除
    delDat(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.$http.post("/system/menu/del", {ids: [row.id]}).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.queryPage_()
        } else {
          this.$message.warning(res.message)
        }
      })
    }
    ,
    delDataS_() {
      if (this.table.defSelectKey.length === 0) {
        this.$message.warn("请至少勾选一项", 1)
        return
      }

      Modal.confirm({
        title: '是否确定删除?',
        icon: createVNode(ExclamationCircleOutlined),
        content: `已勾选${this.table.defSelectKey.length}条数据`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.$http.post("/system/menu/del", {ids: this.table.defSelectKey}).then(res => {
            if (res.status) {
              this.$message.success(res.message)
              this.queryPage_()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
        onCancel: () => {
          this.$message.warning("操作已取消", 1)
        },
      });

    }
    ,
//打开新增
    openAdd_(obj) {
      this.show.insertDialog = true
      this.defResetData()

      //随便任意层级新增
      if (!obj) {
        this.form.defData.pid = "0";
        this.form.defData.pname = "#";
        return
      }

      //添加到指定父级之下
      let row = JSON.parse(JSON.stringify(obj))
      ////////////console.log(row)
      this.form.defData.pid = row.id;
      this.form.defData.pname = row.name;
      this.form.defData.level = row.level * 1 + 1;
      this.form.defData.sort = row.sort * 1 + 10;
    }
    ,
//打开编辑
    openEdit_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.show.editDialog = true
      this.form.defData = row;
    }
    ,
//选择菜单
    selectPMenu(obj) {
      //根路由
      if (!obj) {
        this.form.defData.pid = "0";
        this.form.defData.pname = "#";
        this.form.defData.level = "1";
        this.show.selectPMenu = false;
        return
      }

      //添加到指定父级之下
      let row = JSON.parse(JSON.stringify(obj))
      this.form.defData.pid = row.id;
      this.form.defData.pname = row.name;
      this.form.defData.level = row.level * 1 + 1;
      this.show.selectPMenu = false;
    }
    ,
//重置表单
    resetForm_(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    }
    ,
//初始化表单
    defResetData() {
      this.form.defData = JSON.parse(JSON.stringify(this.form.defResetData))
      // ////////console.log(this.form.defData)
    }
    ,
//表格选中
    defRowSelection_() {
      return {
        type: this.type,
        checkStrictly: false,
        selectedRowKeys: this.table.defSelectKey,
        onChange: (selectedRowKeys, selectedRows) => {
          this.table.defSelectKey = selectedRowKeys
          this.table.defSelectRow = selectedRows
          // ////console.log("defRowSelection_-onChange")
        },
        onSelect: (record, selected, selectedRows) => {
          // ////console.log("defRowSelection_-onSelect")

        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          // ////console.log("defRowSelection_-onSelectAll")
        },
      }
    }
    ,
//表格单击事件
    defClickRow(record) {
      const selectedRowKeys = [...this.table.defSelectKey];
      const selectedRows = [...this.table.defSelectRow];

      //单选
      if (this.type == 'radio') {
        this.table.defSelectKey = [record.id]
        this.table.defSelectRow = [record]
        // ////console.log("defClickRow---radio")
        // ////console.log(this.table.defSelectKey .length)
        // ////console.log(this.table.selectedRows .length)
        return
      }

      //正常
      if (selectedRowKeys.indexOf(record.id) >= 0) {
        selectedRowKeys.splice(selectedRowKeys.indexOf(record.id), 1);
        selectedRows.splice(selectedRowKeys.indexOf(record.id), 1);
      } else {
        selectedRowKeys.push(record.id);
        selectedRows.push(record);
      }
      this.table.defSelectKey = selectedRowKeys;
      this.table.defSelectRow = selectedRows;

      // ////console.log("defClickRow")
      // ////console.log(selectedRowKeys.length)
      // ////console.log(selectedRows.length)

    }
    ,
    //表格单击事件
    defCustomRow(record) {
      return {
        onClick: () => {
          this.defClickRow(record);
        },
      };
    }
    ,
//全屏
    fullScreen() {
      let element = document.getElementById("fullscreen")
      if (screenfull.isEnabled) {
        screenfull.request(element)
      }
      screenfull.toggle()
    }
    ,
    getLevelColor(text) {
      if (text == 1) return '#006d75'
      if (text == 2) return '#13c2c2'
      if (text == 3) return '#52c41a'
      if (text == 4) return '#69c0ff'
      return '#bae7ff'
    }
    ,
  }
})
;
</script>

<style lang="less" scoped>

//:-webkit-scrollbar 滚动条整体部分，可以设置宽度啥的
//::-webkit-scrollbar-button 滚动条两端的按钮
//::-webkit-scrollbar-track  外层轨道
//::-webkit-scrollbar-track-piece  内层滚动槽
//::-webkit-scrollbar-thumb 滚动的滑块
//::-webkit-scrollbar-corner 边角
//::-webkit-resizer 定义右下角拖动块的样式
//
&:deep(::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}


&:deep(::-webkit-scrollbar-thumb) {
  background: rgba(0, 0, 0, .12);
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 5px rgb(0 21 41 / 5%);
}

//::-webkit-scrollbar-thumb {
/* background: hsla(0,0%,100%,.2); */
/* border-radius: 3px; */
/* -webkit-box-shadow: inset 0 0 5px hsl(0deg 0% 100% / 5%); */
//}

//&:deep(::-webkit-scrollbar-track) {
//  background: rgba(0, 0, 0, .06);
/* border-radius: 3px; */
/* -webkit-box-shadow: inset 0 0 5px rgb(0 21 41 / 5%); */
//}

//::-webkit-scrollbar-track {
/* background: hsla(0,0%,100%,.15); */
/* border-radius: 3px; */
/* -webkit-box-shadow: inset 0 0 5px rgb(37 37 37 / 5%); */
//}


</style>
